package com.bxd.baodan.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.item.UserItem;
import com.bxd.baodan.util.AppManager;
import com.bxd.baodan.util.ETUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.LoginIMUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.SaveMsgUtil;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.io.Serializable;
import java.util.Map;

public class RegistActivity extends BaseActivity implements OnClickListener {

    private TextView codeBtn;
    ImageView see;
    private boolean canSeePassword = false;

    private ProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist);
        initView();
    }

    private void initView() {
        setActionBarTitle("注册");
        findViewById(R.id.regist).setOnClickListener(this);
        see = (ImageView) findViewById(R.id.see);
        see.setOnClickListener(this);
        codeBtn = (TextView) findViewById(R.id.code_btn);
        codeBtn.setOnClickListener(this);

        findViewById(R.id.wx_login).setOnClickListener(this);
        findViewById(R.id.qq_login).setOnClickListener(this);
        findViewById(R.id.weibo_login).setOnClickListener(this);
    }


    private EditText getPhone() {
        return (EditText) findViewById(R.id.phone);
    }

    private EditText getCode() {
        return (EditText) findViewById(R.id.code);
    }

    private EditText getPwd() {
        return (EditText) findViewById(R.id.pwd);
    }

    @Override
    public void onClick(View view) {

        String phone, code, pwd;

        switch (view.getId()) {

            case R.id.see:
                canSeePassword = !canSeePassword;
                if (canSeePassword) {
                    // 显示密码
                    see.setImageResource(R.drawable.see_pwd);
                    getPwd().setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    // 隐藏密码
                    see.setImageResource(R.drawable.eyeclosed);
                    getPwd().setInputType(InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                break;


            case R.id.regist:

                phone = getPhone().getText().toString().trim();
                if (phone.isEmpty()) {
                    showToast("请输入手机号");
                    return;
                }
                if (!ETUtil.isMobileNO(getPhone())) {
                    showToast("手机号格式不对");
                    return;
                }
                code = getCode().getText().toString().trim();
                if (code.isEmpty()) {
                    showToast("验证码不能为空");
                    return;
                }
                pwd = getPwd().getText().toString().trim();
                if (pwd.isEmpty()) {
                    showToast("密码不能为空");
                    return;
                }

                //请求成功 ,关闭倒计时
                getRegist(phone, code, pwd);


                break;

            case R.id.code_btn:
                phone = getPhone().getText().toString().trim();
                if (phone.isEmpty()) {
                    showToast("手机号不能为空");
                    return;
                }
                if (!ETUtil.isMobileNO(getPhone())) {
                    showToast("手机号格式不对");
                    return;
                }

                startTime();
                NetUtil netUtil = new NetUtil(this, JsonApi.GET_CHECK_VCODE);
                netUtil.
                        setParams("phone", phone);
                netUtil.setParams("src", "4");
                netUtil.postRequest("正在获取验证码", new NetUtil.RequestStringListener() {
                    @Override
                    public void onComplete(String result) {
//
                    }
                });

                break;

            case R.id.wx_login:
                if (pd == null) {
                    pd = new ProgressDialog(RegistActivity.this);
                    pd.setMessage("登录中...");
                }
                pd.show();
                UMShareAPI.get(RegistActivity.this).getPlatformInfo(RegistActivity.this, SHARE_MEDIA.WEIXIN, authListener);
                break;
            case R.id.qq_login:
                if (pd == null) {
                    pd = new ProgressDialog(RegistActivity.this);
                    pd.setMessage("登录中...");
                }
                pd.show();
                UMShareAPI.get(RegistActivity.this).getPlatformInfo(RegistActivity.this, SHARE_MEDIA.QQ, authListener);
                break;
            case R.id.weibo_login:
                if (pd == null) {
                    pd = new ProgressDialog(RegistActivity.this);
                    pd.setMessage("登录中...");
                }
                pd.show();
                UMShareAPI.get(RegistActivity.this).getPlatformInfo(RegistActivity.this, SHARE_MEDIA.SINA, authListener);
                break;
        }
    }

    private void getRegist(String phone, String code, String pwd) {
        NetUtil netUtil = new NetUtil(this, JsonApi.user_register);


        netUtil.setParams("telphone", phone);
        netUtil.setParams("password", pwd);
        netUtil.setParams("type", 1);
        netUtil.setParams("vcode", code);


        netUtil.postRequest("注册中", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {
                if (JSONUtil.isSuccess(result)) {

                    finish();
                }
            }
        });

    }

    private int time = -1;
    private Boolean isGetVcode = false;

    /**
     * 开始计时
     */
    private void startTime() {
        time = 60;
        isGetVcode = true;
        new Thread() {
            public void run() {
                do {
                    try {
                        Thread.sleep(1 * 1000);
                        if (handler != null) {
                            handler.sendEmptyMessage(--time);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } while (time > 0 && isGetVcode == true);
                time = -1;
                handler.sendEmptyMessage(--time);
            }
        }.start();
    }


    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what > 0) {
                codeBtn.setText(msg.what + "秒后重新获取");
                codeBtn.setEnabled(false);
            } else {
                codeBtn.setText("重新获取验证码");
                codeBtn.setEnabled(true);
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    private void cancelDialog() {
        if (pd != null) {
            pd.cancel();
            pd = null;
        }
    }

    UMAuthListener authListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            String temp = "";
            for (String key : data.keySet()) {
                temp = temp + key + " : " + data.get(key) + "\n";
            }
            LogUtil.e("temp: " + temp);
            String name;
            String iconurl;
            String gender;
            String uid;
            String thirdparty = "";

            name = data.get("name");
            iconurl = data.get("iconurl");
            gender = data.get("gender");
            uid = data.get("uid");


            if (platform.equals(SHARE_MEDIA.QQ)) {
                thirdparty = "qq";
                uid = data.get("uid").trim();
            } else if (platform.equals(SHARE_MEDIA.WEIXIN)) {
                thirdparty = "wechat";
            } else if (platform.equals(SHARE_MEDIA.SINA)) {
                thirdparty = "sina";
            }

            ThirdInfo thirdInfo = new ThirdInfo(thirdparty, name, iconurl, gender, uid);
            cancelDialog();
            thirdLogin(thirdInfo);
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            cancelDialog();
            showToast("第三方登录失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            cancelDialog();
            showToast("取消登录");
        }
    };

    private void thirdLogin(final ThirdInfo info) {
        NetUtil netUtil = new NetUtil(this, JsonApi.THIRD_LOGIN);

        netUtil.setParams("openid", info.uid);
        netUtil.setParams("thirdparty", info.platform);

        netUtil.postRequest("登录中...", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {
                if (JSONUtil.isSuccess(result)) {
                    String isBind = JSONUtil.getData("isbind", JSONUtil.getData(result));
                    if (isBind.equals("0")) {
                        //绑定页面
                        openActivity(BindPhoneActivity.class,
                                new String[]{"thirdinfo"},
                                new String[]{new Gson().toJson(info)});
                    } else {
                        LoginInfo loginInfo = LoginInfo.getInstance(RegistActivity.this);
                        loginInfo.saveUserInfo(JSONUtil.getData(result),
                                App.getContext());
                        UserItem user = LoginInfo.getInstance(
                                App.getContext()).getUser();

                        SaveMsgUtil.updateLocalInfo(user,
                                App.getContext());// 更新用户的登录资料到本地
                        App.getContext().sendBroadcast(
                                new Intent(Constant.ACTION_SUCCESS_LOGIN));
                        App.getContext().sendBroadcast(
                                new Intent(Constant.ACTION_SUCCESS_UPLOAD_INFOR));
                        loginIM();  //IM登录
                        AppManager.getInstance().finishOtherActivity(MainActivity.class);
                    }
                }
            }
        });
    }

    public class ThirdInfo implements Serializable {
        public ThirdInfo(String platform, String name, String iconurl, String gender, String uid) {
            this.name = name;
            this.iconurl = iconurl;
            this.gender = gender;
            this.uid = uid;
            this.platform = platform;
        }

        public String name;
        public String iconurl;
        public String gender;
        public String uid;
        public String platform;

    }

    public void loginIM() {
        LoginIMUtil loginUtil = new LoginIMUtil(AppManager.getInstance().currentActivity());
        loginUtil.initIM();
        loginUtil.setCallback(new LoginIMUtil.Callback() {
            @Override
            public void next() {

            }
        });
        loginUtil.loginIM();
    }
}
